﻿using AutoMapper;
using Basic.Traceability.Domain.Products;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.Products.TraceableProducts;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.Products.TraceableProducts
{
    public class DeleteTraceableProductsHandler : IRequestHandler<DeleteTraceableProductsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<TraceableProductsModel> traceableProductsRepository;
        private readonly IMapper mapper;
        private readonly ILogger<DeleteTraceableProductsHandler> logger;

        public DeleteTraceableProductsHandler(IBaseRepository<TraceableProductsModel> traceableProductsRepository, IMapper mapper, ILogger<DeleteTraceableProductsHandler> logger)
        {
            this.traceableProductsRepository = traceableProductsRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// /删除商品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(DeleteTraceableProductsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            foreach (var item in request.ProductsIds)
            {
                var model = traceableProductsRepository.GetModel(item);
                if (model != null)
                {
                    model.IsDeleted = true;
                    traceableProductsRepository.Update(model);
                    res.Code = APIEnums.Success;
                    res.Msg = "删除商品信息成功";
                    logger.LogInformation("删除商品信息成功");
                    res.Data = 1;
                }
                else
                {
                    res.Code = APIEnums.Fail;
                    res.Msg = "删除商品信息失败";
                    logger.LogError("删除商品信息失败");
                    res.Data = 0;
                }
            }
            return Task.FromResult(res);
        }
    }
}
